﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using fmtx.Framework.Cache;
using com.fmtx.Model;
using com.fmtx.IDal;
using fmtx.Framework.DALFactory;


    public class PictureCache
    {
        private const int SIZE = 500;//片块大小

        /// <summary>
        /// 获取指定的文章缓存列表
        /// </summary>
        /// <param name="maxid"></param>
        /// <param name="size"></param>
        /// <param name="index"></param>
        /// <returns></returns>
        public static List<OutPut> Query(int maxid, int size, string keyword,int index = 0)
        {
            DataCache cache = new DataCache(string.Format(CacheKey.PICTURE_LIST, index));
            IEnumerable<OutPut> list = cache.Get() as IEnumerable<OutPut>;
            if (list == null)
            {
                list = QueryBind(index, SIZE);
                if (list != null || list.Count() > 0)
                {
                    cache.Set(list, 24 * 60 * 3);
                }
            }
            if (list != null && list.Count() != 0)
            {
                list = list.Where(m => m.IsUp == true);
            }
            if (maxid > 0 && list != null && list.Count() != 0)
            {
                list = list.Where(m => m.Id < maxid);
            }
            if (!string.IsNullOrEmpty(keyword))
            {
                list = list.Where(w => (w.KeyWord != null && w.KeyWord.Contains(keyword)) || (w.Address != null && w.Address.Contains(keyword)) || (w.Title != null && w.Title.Contains(keyword)));
            }
            List<OutPut> resultlist = list.OrderByDescending(o => o.Id).Take(size).ToList();
            DataCache acount = new DataCache(CacheKey.PICTURE_COUNT);
            var allcount = acount.Get();
            if (allcount == null)
            {
                IArticle _article = DataAccess<IArticle>.GetObject();
                allcount = _article.GetCount();
                acount.SetByTime(allcount, 1 * 60);
            }
            int cusize = StaticCs.GetCuSize((int)allcount, SIZE);
            var cc = size - resultlist.Count;
            if (cc > 0 && cusize>index)
            {
                var olist = Query(maxid, cc, keyword, index + 1);
                if (olist != null && olist.Count != 0)
                {
                    resultlist.AddRange(olist);
                }
            }
            return resultlist.ToList();
        }

        /// <summary>
        /// 插入一个图片
        /// </summary>
        /// <param name="model"></param>
        public static void Insert(Picture model)
        {
            DataCache cache = new DataCache(string.Format(CacheKey.PICTURE_LIST, 0));
            List<OutPut> list = cache.Get() as List<OutPut>;
            if (list != null)
            {
                list.Add(BindDetail(model));
            }
        }

        /// <summary>
        /// 更新一个图片缓存
        /// </summary>
        /// <param name="id"></param>
        /// <param name="index"></param>
        public static void Update(Picture bean, int index = 0)
        {
            DataCache acount = new DataCache(CacheKey.PICTURE_COUNT);
            var allcount = acount.Get();
            if (allcount == null)
            {
                IArticle _article = DataAccess<IArticle>.GetObject();
                allcount = _article.GetCount();
                acount.SetByTime(allcount, 1 * 60);
            }
            int cusize = StaticCs.GetCuSize((int)allcount, SIZE);

            DataCache cache = new DataCache(string.Format(CacheKey.PICTURE_LIST, index));
            List<OutPut> list = cache.Get() as List<OutPut>;
            if (list != null)
            {
                var model = list.Where(w => w.Id == bean.Id).FirstOrDefault();
                if (model == null && cusize > index)
                {
                    Update(bean, index++);
                }
                model.Title = bean.Title;
            }
            else if (cusize > index)
            {
                Update(bean, index++);
            }
        }

        /// <summary>
        /// 移除一个图片缓存
        /// </summary>
        /// <param name="id"></param>
        /// <param name="index"></param>
        public static void Remove(int id, int index = 0)
        {
            DataCache acount = new DataCache(CacheKey.PICTURE_COUNT);
            var allcount = acount.Get();
            if (allcount == null)
            {
                IArticle _article = DataAccess<IArticle>.GetObject();
                allcount = _article.GetCount();
                acount.SetByTime(allcount, 1 * 60);
            }
            int cusize = StaticCs.GetCuSize((int)allcount, SIZE);

            DataCache cache = new DataCache(string.Format(CacheKey.PICTURE_LIST, index));
            List<OutPut> list = cache.Get() as List<OutPut>;
            if (list != null)
            {
                var model = list.Where(w => w.Id == id).FirstOrDefault();
                if (model == null&&cusize>index)
                {
                    Remove(id, index++);
                }
                model.IsUp = false;
            }
            else if (cusize > index)
            {
                Remove(id, index++);
            }
        }

        /// <summary>
        /// 移除一个相册图片缓存
        /// </summary>
        /// <param name="id"></param>
        /// <param name="index"></param>
        public static void RemoveType(int id, int index = 0)
        {
            DataCache acount = new DataCache(CacheKey.PICTURE_COUNT);
            var allcount = acount.Get();
            if (allcount == null)
            {
                IArticle _article = DataAccess<IArticle>.GetObject();
                allcount = _article.GetCount();
                acount.SetByTime(allcount, 1 * 60);
            }
            int cusize = StaticCs.GetCuSize((int)allcount, SIZE);

            DataCache cache = new DataCache(string.Format(CacheKey.PICTURE_LIST, index));
            List<OutPut> list = cache.Get() as List<OutPut>;
            if (list != null)
            {
                var models = list.Where(w => w.TypeId == id);
                if (models != null)
                {
                    foreach (var item in models)
                    {
                        item.IsUp = false;
                    }
                }
                else if(cusize>index)
                {
                    RemoveType(id, index++);
                }
            }
            else if (cusize > index)
            {
                RemoveType(id, index++);
            }
        }

        /// <summary>
        /// 赞美图片
        /// </summary>
        /// <param name="model"></param>
        public static void DoSup(int id, int index = 0)
        {
            DataCache acount = new DataCache(CacheKey.PICTURE_COUNT);
            var allcount = acount.Get();
            if (allcount == null)
            {
                IArticle _article = DataAccess<IArticle>.GetObject();
                allcount = _article.GetCount();
                acount.SetByTime(allcount, 1 * 60);
            }
            int cusize = StaticCs.GetCuSize((int)allcount, SIZE);

            DataCache cache = new DataCache(string.Format(CacheKey.PICTURE_LIST, index));
            List<OutPut> list = cache.Get() as List<OutPut>;
            if (list != null)
            {
                var abean = list.Where(w => w.Id == id).FirstOrDefault();
                if (abean != null)
                {
                    abean.SupCount++;
                }
                else if (cusize > index)
                {
                    DoSup(id, index++);
                }
            }
            else if (cusize > index)
            {
                DoSup(id, index++);
            }
        }

        /// <summary>
        /// 插入评论
        /// </summary>
        /// <param name="model"></param>
        public static void InsertComment(Comment model, int index = 0)
        {
            DataCache cache = new DataCache(string.Format(CacheKey.PICTURE_LIST, index));
            List<OutPut> list = cache.Get() as List<OutPut>;
            if (list != null)
            {
                var abean = list.Where(w => w.Id == model.TagId).FirstOrDefault();
                if (abean != null)
                {
                    if (abean.Comments == null)
                    {
                        abean.Comments = new List<Comments>();
                    }
                    abean.Comments.Add(BindComment(model));
                    if (abean.Comments.Count > 3)
                    {
                        abean.Comments.RemoveAt(0);
                    }
                }
                else
                {
                    InsertComment(model, index++);
                }
            }
        }

        /// <summary>
        /// 移除评论
        /// </summary>
        /// <param name="aid">文章id</param>
        /// <param name="id">评论id</param>
        public static void RemoveComment(int aid, int id, int index = 0)
        {
            DataCache cache = new DataCache(string.Format(CacheKey.PICTURE_LIST, index));
            List<OutPut> list = cache.Get() as List<OutPut>;
            if (list != null)
            {
                var abean = list.Where(w => w.Id == aid).FirstOrDefault();
                if (abean != null)
                {
                    if (abean.Comments != null)
                    {
                        abean.Comments.Where(w => w.Id == id).FirstOrDefault().IsUp = false;
                    }
                }
                else
                {
                    RemoveComment(aid, id, index++);
                }
            }
        }

        /// <summary>
        /// 单元数据绑定
        /// </summary>
        /// <param name="bean"></param>
        /// <returns></returns>
        public static OutPut BindDetail(Picture bean)
        {
            IUserInfo user = DataAccess<IUserInfo>.GetObject();
            IComment comment = DataAccess<IComment>.GetObject();
            IPictureType picturetype = DataAccess<IPictureType>.GetObject();
            var u = user.Get(bean.Uid);
            OutPut model = new OutPut();
            model.Id = bean.Id;
            model.Title = bean.Title;
            model.Time = bean.InTime.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss");
            model.Pic = bean.PicAddress;
            model.Scale = bean.Scale;
            model.Uid = bean.Uid;
            model.Uname = u.Name;
            model.Header = u.Header;
            model.SupCount = bean.PraiseCount;
            model.CommentCount = bean.CommentCount;
            var ptype = picturetype.Get(bean.TypeId);
            model.Address = bean.Address;
            model.AddressUrl = bean.AddressUrl;
            model.IsUp = true;
            model.IsSys = u.IsSystem;
            model.KeyWord = ptype.KeyWord;
            model.TypeId = bean.TypeId;
            var clist = comment.Query(bean.Id, Target.PICTRUE, 0, 3);
            model.Comments = new List<Comments>();
            foreach (var item in clist)
            {
                model.Comments.Add(BindComment(item));
            }
            return model;
        }

        /// <summary>
        /// 绑定单个评论
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public static Comments BindComment(Comment model)
        {
            IUserInfo user = DataAccess<IUserInfo>.GetObject();
            Comments c = new Comments();
            c.Id = model.Id;
            c.Content = model.Content;
            c.Ip = model.Ip;
            c.Time = model.InTime.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss");
            c.Uid = model.Uid;
            var cu = user.Get(model.Uid);
            c.Uname = cu.Name;
            c.Header = cu.Header;
            return c;
        }

        /// <summary>
        /// 绑定图片数据
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public static List<OutPut> QueryBind(int index, int size)
        {
            IPicture pictrue = DataAccess<IPicture>.GetObject();
            var alist = pictrue.Query(index, size);
            List<OutPut> output = new List<OutPut>();
            foreach (var item in alist)
            {
                if (item.Scale > 0)
                {
                    output.Add(BindDetail(item));
                }
            }
            return output;
        }

        /// <summary>
        /// 获取今日关键字相关图片
        /// </summary>
        /// <param name="size"></param>
        /// <returns></returns>
        public static IList<Picture> GetListByKeyword(int size)
        {
            DataCache cach = new DataCache(CacheKey.PICTURE_KEYWORD_LIST);
            var list = cach.Get() as IList<Picture>;
            if (list == null)
            {
                IKeyWord _keyword = DataAccess<IKeyWord>.GetObject();
                List<string> keywords = _keyword.QueryHost(20, Target.PICTRUE).Select(s => s.Keyword).ToList();
                var randem = new Random((int)DateTime.Now.Ticks);
                var num = randem.Next(0, keywords.Count - 1);
                IPicture picture = DataAccess<IPicture>.GetObject();
                list = picture.QueryByKeyword(size, keywords[num]);
                if (list != null && list.Count > 0)
                {
                    cach.Set(list, 24 * 60);
                }
            }
            return list;
        }
    }

   
